package im

import (
	"awesomeProject1/push/plugin"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"sync"
	"time"
)

type WsImService struct {
}

func NewWsImService() *WsImService {
	return &WsImService{}
}

var (
	upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			// 取消ws跨域校验
			// 允许所有的请求来源，实际生产中需要根据实际情况判断是否允许
			return true
		},
		ReadBufferSize:   1024,
		WriteBufferSize:  1024,
		HandshakeTimeout: 5 * time.Second,
	}
	connections = make(map[string]*websocket.Conn)
	mu          sync.Mutex
)

type WSController interface {
	HandleWebSocket(ctx *gin.Context)
}

// TODO 处理 WebSocket 连接
func (ws WsImService) HandleWebSocket(c *gin.Context) {
	log.Println("==============>ws开始连接")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("===============>协议升级出错啦！！！", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 获取 WebSocket ID，假设从请求参数中获取
	websocketID := c.Query("websocketID")

	mu.Lock()
	connections[websocketID] = conn
	mu.Unlock()

	log.Println("==============>ws连接成功ID为", websocketID)

	go handleMessages(conn)
}

// TODO 处理接收到的消息 比如脱敏
func handleMessages(conn *websocket.Conn) {
	defer conn.Close()

	for {
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			return
		}

		// 例如：处理收到的文本消息
		if messageType == websocket.TextMessage {
			message := string(p)
			log.Println("=============>收到一个文本消息:  ", message)
			// 处理消息逻辑
			// 例如：广播消息给其他连接
			// broadcastMessage(message)
		}
	}
}

// TODO 私发信息
func sendMessageToClient(websocketID string, message string) {
	mu.Lock()
	defer mu.Unlock()

	conn, exists := connections[websocketID]
	if exists {
		err := conn.WriteMessage(websocket.TextMessage, []byte(message))
		if err != nil {
			log.Println("Error sending message to client:", err)
		}
	}
}

// TODO 群发信息
func groupMessage(websocketIDs []string, message string) {
	log.Println("=========================>开始群发消息wsID为", websocketIDs)
	mu.Lock()
	defer mu.Unlock()

	// 遍历连接id,获得连接并发送消息
	for i := 0; i < len(websocketIDs); i++ {
		conn, exists := connections[websocketIDs[i]]
		if exists {
			err := conn.WriteMessage(websocket.TextMessage, []byte(message))
			if err != nil {
				log.Println("Error broadcasting message:", err)
				continue
			}
		}
	}
}

// TODO 广播信息 把消息广播给所有已经连接websocket的用户
func broadcastMessage(message string) {
	mu.Lock()
	defer mu.Unlock()

	// 遍历所有连接，发送消息
	for _, conn := range connections {
		err := conn.WriteMessage(websocket.TextMessage, []byte(message))
		if err != nil {
			log.Println("Error broadcasting message:", err)
		}
	}
}

func (ws *WsImService) SendMessage(info plugin.MessageInfo) error {
	groupMessage(info.Receiver, info.Message)
	return nil
}

//func main() {
//	app := gin.Default()
//
//	// 设置 WebSocket 路由
//	app.GET("/ws")
//
//	// 启动服务
//	app.Run(":8080")
//}
